package com.ruoyi.web.controller.tool;


import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.HashMap;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.validation.constraints.Pattern.Flag;



import org.checkerframework.checker.units.qual.g;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.api.client.repackaged.com.google.common.annotations.GwtCompatible;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.web.core.config.JDCloudOSS;

import gui.ava.html.image.generator.HtmlImageGenerator;


public class QRCodeCreate {
	private static final Logger log = LoggerFactory.getLogger(QRCodeCreate.class);
	/**
	 * 黑色
	 */
	private static final int BLACK = 0xFF000000;
	/**
	 * 白色
	 */
	private static final int WHITE = 0xFFFFFFFF;
	/**
	 * 宽
	 */
	private static final int WIDTH = 300;
	/**
	 * 高
	 */
	private static final int HEIGHT = 300;

	public String CodeCrete(String companyCode, String path) {
		// 定义要生成二维码的基本参数
		int width = 300;
		int height = 300;
		String type = "png";
		String content = companyCode;
		String imgPath = path+"/"+content+"/"+content+".png";
		// 定义二维码的配置，使用HashMap
		HashMap hints = new HashMap();
		// 字符集，内容使用的编码
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		// 容错等级，H、L、M、Q
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 边距，二维码距离边的空白宽度
		hints.put(EncodeHintType.MARGIN, 2);

		try {
		    // 生成二维码对象，传入参数：内容、码的类型、宽高、配置
		    BitMatrix bitMatrix =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		    // 定义一个路径对象
		    Path file = new File(imgPath).toPath();
		    imgPath =path+"/"+content+"/";
			File dosc = new File(imgPath); 
			if (!dosc.exists()) {
				dosc.mkdirs();
			}
			imgPath = content+".png";
		    // 生成二维码，传入二维码对象、生成图片的格式、生成的路径
		    MatrixToImageWriter.writeToPath(bitMatrix, type, file);
		} catch (WriterException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return imgPath;
	}
	
	public String companyCodeCrete(String companyCode,String companyCodeBar, String path) {
		// 定义要生成二维码的基本参数
		int width = 300;
		int height = 300;
		String type = "png";
		String content = companyCode;
		String imgPath = path+"/"+companyCodeBar+"/"+content+".png";
		// 定义二维码的配置，使用HashMap
		HashMap hints = new HashMap();
		// 字符集，内容使用的编码
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		// 容错等级，H、L、M、Q
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 边距，二维码距离边的空白宽度
		hints.put(EncodeHintType.MARGIN, 2);

		try {
		    // 生成二维码对象，传入参数：内容、码的类型、宽高、配置
		    BitMatrix bitMatrix =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		    // 定义一个路径对象
		    Path file = new File(imgPath).toPath();
		    imgPath =path+"/"+content+"/";
			File dosc = new File(imgPath); 
			if (!dosc.exists()) {
				dosc.mkdirs();
			}
			imgPath = content+".png";
		    // 生成二维码，传入二维码对象、生成图片的格式、生成的路径
		    MatrixToImageWriter.writeToPath(bitMatrix, type, file);
		} catch (WriterException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return imgPath;
	}
	
	/**
	 * 
	 * @param companyCode 二维码内容
	 * @param imaName 二维码名称
	 * @param path 保存路径
	 * @return
	 * @throws Exception 
	 */
	public String daptCodeCrete(String companyCode,String imaName, String path) {
		// 定义要生成二维码的基本参数
		int width = 300;
		int height = 300;
		String type = "png";
		String content = companyCode;
		String imgPath = path+"/"+imaName+"/"+imaName+".png";
		// 定义二维码的配置，使用HashMap
		HashMap hints = new HashMap();
		// 字符集，内容使用的编码
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		// 容错等级，H、L、M、Q
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 边距，二维码距离边的空白宽度
		hints.put(EncodeHintType.MARGIN, 2);

		try {
		    // 生成二维码对象，传入参数：内容、码的类型、宽高、配置
		    BitMatrix bitMatrix =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		    // 定义一个路径对象
		    Path file = new File(imgPath).toPath();
		    //imgPath =path+"/"+imaName+"/";
			File dosc = new File(imgPath); 
			if (!dosc.exists()) {
				dosc.mkdirs();
			}
			
		    // 生成二维码，传入二维码对象、生成图片的格式、生成的路径
		    MatrixToImageWriter.writeToPath(bitMatrix, type, file);
		    imgPath = imaName+".png";
		} catch (WriterException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return imgPath;
	}
	
	
	public String regCodeCrete(String serialNum,String companyCode,String imaName, String path) throws Exception {
		// 定义要生成二维码的基本参数
		int width = 300;
		int height = 300;
		String type = "png";
		String content = companyCode;
		String imgPath = path+"/"+imaName+".png";
		// 定义二维码的配置，使用HashMap
		HashMap hints = new HashMap();
		// 字符集，内容使用的编码
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		// 容错等级，H、L、M、Q
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 边距，二维码距离边的空白宽度
		hints.put(EncodeHintType.MARGIN, 3);

		try {
		    // 生成二维码对象，传入参数：内容、码的类型、宽高、配置
		    BitMatrix bitMatrix =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		    // 定义一个路径对象
		    Path file = new File(imgPath).toPath();
		    //imgPath =path+"/"+imaName+"/";
			File dosc = new File(imgPath); 
			if (!dosc.exists()) {
				dosc.mkdirs();
			}
			
		    // 生成二维码，传入二维码对象、生成图片的格式、生成的路径
		    MatrixToImageWriter.writeToPath(bitMatrix, type, file);
		    pressText(serialNum, dosc, 5, Color.BLACK, 18);
		    imgPath = imaName+".png";
		} catch (WriterException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return imgPath;
	}
	
	
	
	
	
	
	
	
	
	/**
	 * 
	 * @param companyCode 二维码内容
	 * @param imaName 二维码名称
	 * @param path 保存路径
	 * @return
	 * @throws Exception 
	 */
	public String addTextCodeCreteByCreateCompany(String companyCode,String imaName, String path, String companyName) throws Exception {
		// 定义要生成二维码的基本参数
		int width = 300;
		int height = 300;
		String type = "png";
		String content = companyCode;
		String imgPath = path+"/company/"+imaName+"/"+imaName+".png";
		// 定义二维码的配置，使用HashMap
		HashMap hints = new HashMap();
		// 字符集，内容使用的编码
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		// 容错等级，H、L、M、Q
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 边距，二维码距离边的空白宽度
		hints.put(EncodeHintType.MARGIN, 4);

		try {
		    // 生成二维码对象，传入参数：内容、码的类型、宽高、配置
		    BitMatrix bitMatrix =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		    // 定义一个路径对象
		    Path file = new File(imgPath).toPath();
		    //imgPath =path+"/"+imaName+"/";
			File dosc = new File(imgPath); 
			if (!dosc.exists()) {
				dosc.mkdirs();
			}
			
		    // 生成二维码，传入二维码对象、生成图片的格式、生成的路径
		    MatrixToImageWriter.writeToPath(bitMatrix, type, file);
		    String imgContent = companyName;
		    //pressText(imgContent, dosc, 5, Color.BLACK, 20);
		    pressText(imgContent, dosc, 5, Color.BLACK, 20);

		    // 原先的代码
			// imgPath = imaName+".png";
			// 修改后的代码
		    // 将生成的二维码图片上传到京东云OSS
			//JDCloudOSS oss = new JDCloudOSS();
			//imgPath = oss.uploadFileJDCloud(imgPath);

		} catch (WriterException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return imgPath;
	}
	
	/**
	 * 
	 * @param companyCode 二维码内容
	 * @param imaName 二维码名称
	 * @param path 保存路径
	 * @return
	 * @throws Exception 
	 */
	public String addTextCodeCreteByCreateDept(String companyCode,String imaName, String path, String companyName, String deptName) throws Exception {
		// 定义要生成二维码的基本参数
		int width = 300;
		int height = 300;
		String type = "png";
		String content = companyCode;
		String imgPath = path+"/"+imaName+"/"+imaName+".png";
		String imgPathJd ="";
		// 定义二维码的配置，使用HashMap
		HashMap hints = new HashMap();
		// 字符集，内容使用的编码
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		// 容错等级，H、L、M、Q
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		// 边距，二维码距离边的空白宽度
		hints.put(EncodeHintType.MARGIN, 4);

		try {
		    // 生成二维码对象，传入参数：内容、码的类型、宽高、配置
		    BitMatrix bitMatrix =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		    // 定义一个路径对象
		    Path file = new File(imgPath).toPath();
			File dosc = new File(imgPath);
			if (!dosc.exists()) {
				dosc.mkdirs();
			}
			
		    // 生成二维码，传入二维码对象、生成图片的格式、生成的路径
		    MatrixToImageWriter.writeToPath(bitMatrix, type, file);
		    //String imgContent = deptName;
		    //System.err.println(imgContent);
		    //pressText(imgContent, dosc, 5, Color.BLACK, 22);
		    //pressText(imgContent, dosc, 5, Color.BLACK, 24);

		    // 将二维码合并到html，重新生成图片，然后再上传京东云
			String filename = imaName + "/" + imaName + ".png";
			String localPath=RuoYiConfig.getUploadPath()+"/"+filename;
			System.out.println("-------local图片地址："+localPath);
			JDCloudOSS oss = new JDCloudOSS();
			String url = oss.uploadFileJDCloud(imgPath);
			//InetAddress addr = InetAddress.getLocalHost();
			//String url = "http://" + addr.getHostAddress() + ":8088/icon/" + filename;
			
			System.out.println("-------url图片地址："+url);
			
			imgPath = createDepartmentCode(companyName, url, imgPath);
			// 不上传京东云，使用映射
			//String localPath = imgPath.split("uploadPath/")[1];
			//imgPath = "/icon/" + localPath;
			// 将生成的二维码图片上传到京东云OSS
			//JDCloudOSS oss = new JDCloudOSS();
			//imgPath = oss.uploadFileJDCloud(imgPath);
			
			// 将生成的二维码图片上传到京东云OSS
	           //JDCloudOSS oss = new JDCloudOSS();
	           imgPathJd = oss.uploadFileJDCloud(imgPath);
		} catch (WriterException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return imgPathJd;
	}
	
	
	public  String createDepartmentCode(String title,
            String url,
            String path) {
		// PS：现有的框架兼容性很差，有很多css样式不支持，所以有的样式用空格替代
		String HtmlTemplateStr =
		"    <html>" +
		"        <style> " +
		"            *{margin:0;padding:0}" +
		"            body {width: 800px;height:1000px;font-family:\"Microsoft Yahei\";}" +
		"            h1 {color:#FFFFFF;}" +
		"            h2 {color: #7F7F7F}" +
		"            p.title {margin-top:-10px;background-color: #00B0F0; padding: 95px;color:#FFFFFF;text-align: center;font-size: 60px;font-weight: 500;}" +
		"            #platform-code {text-align: center;margin: 50 auto;}" +
		"            #desc {text-align: left;color:#808080;padding: 0 90px;font-size: 35px;line-height:300%}" +
		"            #blank {width:100%;height:200px}" +
		"            #bottom{width: 100%;bottom:0px;left:0px;margin: 0 auto;padding-left: 60px}" +
		"         </style>" +
		"         <body>" +
		"            <p class=\"title\">" + title + "</p>" +
		"            <div id=\"platform-code\">" +
		"                <img width=\"600\" height=\"600\" src=\"" + url + "\"></img>" +
		"                <div style=\"width:100%;height:50px\"></div>" +
		"                <p id=\"desc\">扫码二维码参与活动。</p>" +
		"            </div>" +
		"            <div id=\"blank\">" +
		"            </div>" +
		"            <div id=\"bottom\">" +
		"               <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
		"               <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
		"               <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
		"               <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
		"               <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
		"               <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
		"               <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
		"               <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>" +
		"            </div>" +
		"            </body>" +
		"    </html>";
		
		HtmlImageGenerator imageGenerator = new HtmlImageGenerator();
		imageGenerator.loadHtml(HtmlTemplateStr);
		// 直接覆盖掉二维码图片（因为二维码图片已经与html合并到一起，无需再保留一张二维码图片）
		imageGenerator.saveAsImage(path);
		return path;
		}
	
	
	public static void pressText(String pressText, File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
		//log.info("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		//System.out.println("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		 //pressText = new String(pressText.getBytes(), "utf-8");
		 //log.info("--------------pressText---utf-8------"+pressText);
		 Image src = ImageIO.read(qrFile);
		 int imageW = src.getWidth(null);
		 int imageH = src.getHeight(null);
		 BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
		 Graphics g = image.createGraphics();
		 g.drawImage(src, 0, 0, imageW, imageH, null);
		 //设置画笔的颜色
		 g.setColor(color);
		 //设置字体
		 Font font = new Font("微软雅黑", fontStyle, fontSize);
		 FontMetrics metrics = g.getFontMetrics(font);
		 //文字在图片中的坐标 这里设置在中间
		 int startX = (WIDTH - metrics.stringWidth(pressText))/2;
		 int startY = HEIGHT-15;
		 g.setFont(font);
		 g.drawString(pressText, startX, startY);
		 g.dispose();
		 FileOutputStream out = new FileOutputStream(qrFile);
		 ImageIO.write(image, "JPEG", out);
		 out.close();
	}
	public static void pressText1(String pressText, File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
		//log.info("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		//System.out.println("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		 //pressText = new String(pressText.getBytes(), "utf-8");
		 //log.info("--------------pressText---utf-8------"+pressText);
		 Image src = ImageIO.read(qrFile);
		 int imageW = src.getWidth(null);
		 int imageH = src.getHeight(null);
		 BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
		 Graphics g = image.createGraphics();
		 g.drawImage(src, 0, 0, imageW, imageH, null);
		 //设置画笔的颜色
		 g.setColor(color);
		 //设置字体
		 Font font = new Font("微软雅黑", fontStyle, fontSize);
		 FontMetrics metrics = g.getFontMetrics(font);
		 //文字在图片中的坐标 这里设置在中间
		 int startX = 50;
		 int startY = HEIGHT-30;
		 g.setFont(font);
		 g.drawString(pressText, startX, startY);
		 g.dispose();
		 FileOutputStream out = new FileOutputStream(qrFile);
		 ImageIO.write(image, "JPEG", out);
		 out.close();
		}
	
	public static void pressText2(String pressText, File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
		//log.info("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		//System.out.println("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		 //pressText = new String(pressText.getBytes(), "utf-8");
		 //log.info("--------------pressText---utf-8------"+pressText);
		 Image src = ImageIO.read(qrFile);
		 int imageW = src.getWidth(null);
		 int imageH = src.getHeight(null);
		 BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
		 Graphics g = image.createGraphics();
		 g.drawImage(src, 0, 0, imageW, imageH, null);
		 //设置画笔的颜色
		 g.setColor(color);
		 //设置字体
		 Font font = new Font("微软雅黑", fontStyle, fontSize);
		 FontMetrics metrics = g.getFontMetrics(font);
		 //文字在图片中的坐标 这里设置在中间
		 int startX = 50;
		 int startY = HEIGHT-5;
		 g.setFont(font);
		 g.drawString(pressText, startX, startY);
		 g.dispose();
		 FileOutputStream out = new FileOutputStream(qrFile);
		 ImageIO.write(image, "JPEG", out);
		 out.close();
		}
	
	public static void pressTextClass(String className,String classDate,String startTime,String endTime, File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
		//log.info("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		//System.out.println("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		 //pressText = new String(pressText.getBytes(), "utf-8");
		 //log.info("--------------pressText---utf-8------"+pressText);
		 Image src = ImageIO.read(qrFile);
		 int imageW = src.getWidth(null);
		 int imageH = src.getHeight(null);
		 BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
		 Graphics g = image.createGraphics();
		 g.drawImage(src, 0, 0, imageW, imageH, null);
		 //设置画笔的颜色
		 g.setColor(color);
		 //设置字体
		 Font font = new Font("微软雅黑", fontStyle, fontSize);
		 FontMetrics metrics = g.getFontMetrics(font);
		 //文字在图片中的坐标 这里设置在中间
		 int startX = 60;
		 int startY = HEIGHT-45;
		 g.setFont(font);
		 g.drawString("课程 :"+className, startX, startY);
		 g.drawString("日期 :"+classDate, startX, startY+20);
		 g.drawString("时间 :"+startTime+"~"+endTime, startX, startY+40);
		 g.dispose();
		 FileOutputStream out = new FileOutputStream(qrFile);
		 ImageIO.write(image, "JPEG", out);
		 out.close();
		}
	
	public static void pressTextTeam(String teamName,File qrFile, int fontStyle, Color color, int fontSize) throws Exception {
		//log.info("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		//System.out.println("--------------pressText---in------"+pressText+"----------fontStyle-----"+fontStyle);
		 //pressText = new String(pressText.getBytes(), "utf-8");
		 //log.info("--------------pressText---utf-8------"+pressText);
		 Image src = ImageIO.read(qrFile);
		 int imageW = src.getWidth(null);
		 int imageH = src.getHeight(null);
		 BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
		 Graphics g = image.createGraphics();
		 g.drawImage(src, 0, 0, imageW, imageH, null);
		 //设置画笔的颜色
		 g.setColor(color);
		 //设置字体
		 Font font = new Font("微软雅黑", fontStyle, fontSize);
		 FontMetrics metrics = g.getFontMetrics(font);
		 //文字在图片中的坐标 这里设置在中间
		 int startX = 60;
		 int startY = HEIGHT-45;
		 g.setFont(font);
		 g.drawString("共享区名称 :", startX, startY);
		 g.drawString(teamName, startX, startY+20);
		 g.dispose();
		 FileOutputStream out = new FileOutputStream(qrFile);
		 ImageIO.write(image, "JPEG", out);
		 out.close();
		}
	
	

}
